<?php

namespace App\Http\Controllers;

use App\Models\Budget;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BudgetController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $budgets = Auth::user()->budgets()->orderBy('year', 'desc')->orderBy('month', 'desc')->get();
        
        return response()->json($budgets);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'year' => 'required|integer|min:' . date('Y'),
            'month' => 'required|integer|min:1|max:12',
        ]);

        // 检查是否已存在相同年月的预算
        $existingBudget = Auth::user()->budgets()->where('year', $validated['year'])
            ->where('month', $validated['month'])
            ->first();

        if ($existingBudget) {
            return response()->json(['message' => '该月份的预算已存在'], 409);
        }

        $budget = new Budget($validated);
        $budget->user_id = Auth::id();
        $budget->balance = $validated['amount']; // 初始余额等于预算金额
        $budget->save();

        return response()->json($budget, 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(Budget $budget)
    {
        if ($budget->user_id !== Auth::id()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }
        
        return response()->json($budget);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Budget $budget)
    {
        if ($budget->user_id !== Auth::id()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'year' => 'required|integer|min:' . date('Y'),
            'month' => 'required|integer|min:1|max:12',
        ]);

        // 检查是否已存在相同年月的预算（排除当前预算）
        $existingBudget = Auth::user()->budgets()
            ->where('id', '!=', $budget->id)
            ->where('year', $validated['year'])
            ->where('month', $validated['month'])
            ->first();

        if ($existingBudget) {
            return response()->json(['message' => '该月份的预算已存在'], 409);
        }

        $budget->update($validated);
        
        // 如果预算金额发生变化，需要相应调整余额
        $difference = $validated['amount'] - $budget->getOriginal('amount');
        $budget->balance += $difference;
        $budget->save();

        return response()->json($budget);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Budget $budget)
    {
        if ($budget->user_id !== Auth::id()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }
        
        $budget->delete();

        return response()->json(['message' => '预算删除成功']);
    }
}